package com.example.androidproject.ui.activity;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.androidproject.MyApp;
import com.example.androidproject.R;
import com.example.androidproject.widget.MyVideoView;
import com.example.androidproject.widget.RingProgressBar;
import com.hyg.base.ui.base.BaseActivity;
import com.hyg.base.ui.base.BasePresenter;
import com.hyg.base.utils.SaveFileUtils;
import com.hyg.base.utils.StickersListener;
import com.hyg.common.utils.DateUtils;
import com.hyg.common.utils.FileUtils;
import com.hyg.common.utils.LogUtils;
import com.hyg.common.utils.ToastUtils;
import com.hyg.common.utils.glide.GlideUtils;
import com.liulishuo.okdownload.DownloadTask;

import java.io.File;

public class VideoPlayActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG = "VideoPlayActivity";
    private MyVideoView videoView;//视频
    private String thumbUrl;
    private String videoUrl;
    private String localPath;
    private SeekBar seekBar;//控制面板 进度条
    private TextView current, total;//当前时间 总时间
    private long lastPosition = 0;//
    private ImageView img_play;
    private ImageView img_loading;
    private ImageView iv_button;
    private RelativeLayout rlDownLoadState;
    private ImageView ivThumb;
    private RingProgressBar ringProgressBar;
    private RelativeLayout rl_bottom;

    public String DOWNLOAD_PATH = FileUtils.getFilesPath(MyApp.getApp()) + "/download/";
    private DownloadTask downloadTask;
    private boolean isDownloading = false;

    public static void launch(Context from,String videoUrl){
        VideoPlayActivity.launch(from,"",videoUrl);
    }
    public static void launch(Context from,String thumbUrl,String videoUrl){
        Intent intent = new Intent(from, VideoPlayActivity.class);
        intent.putExtra("thumbUrl",thumbUrl);
        intent.putExtra("videoUrl", GlideUtils.getFixUrl(videoUrl));
        from.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_video_play;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.black), 0);
        this.initVideoPlay();
        rl_bottom = findViewById(R.id.rl_bottom);
        rl_bottom.setVisibility(View.GONE);
    }

    // VideoView 释放资源
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name))
                    return getApplicationContext().getSystemService(name);
                return super.getSystemService(name);
            }
        });
    }

    public void restart(View view) {
        // 播放过 才可以重新开始
        LogUtils.d(TAG, "Video Restart");
        if (videoView != null && videoView.getCurrentPosition() > 0) {
            videoView.seekTo(0);
            videoView.start();
        }
    }

    public void start(View view) {
        LogUtils.d(TAG, "Video Start");
        // 只有不是播放状态才可以start
        if (videoView != null && !videoView.isPlaying()) {
            videoView.start();
        }
    }

    public void pause(View view) {
        // 正在播放 暂停
        LogUtils.d(TAG, "Video Pause");
        if (videoView != null && videoView.isPlaying()) {
            videoView.pause();
        }
    }

    private void initVideoPlay() {
        if (getIntent() != null) {
            thumbUrl = getIntent().getStringExtra("thumbUrl");
            videoUrl = getIntent().getStringExtra("videoUrl");
            localPath = getIntent().getStringExtra("localPath");
            if(!TextUtils.isEmpty(videoUrl)){
                if(!(videoUrl.startsWith("http://") || videoUrl.startsWith("https://"))){
                    videoUrl = GlideUtils.getFixUrl(videoUrl);
                }
            }
            if(!TextUtils.isEmpty(videoUrl) && TextUtils.isEmpty(localPath)){
                localPath = FileUtils.getDownFilePath(videoUrl, DOWNLOAD_PATH,1024);
            }
        }
        videoView = findViewById(R.id.videoView);
        rlDownLoadState = findViewById(R.id.rlThumb);
        ivThumb = findViewById(R.id.ivThumb);
        ringProgressBar = findViewById(R.id.progressBar);
        //返回
        seekBar = findViewById(R.id.seekBar);
        current = findViewById(R.id.current);
        total = findViewById(R.id.total);
        img_play = findViewById(R.id.record_play);
        img_play.setEnabled(false);
        img_loading = findViewById(R.id.img_loading);
        iv_button = findViewById(R.id.iv_button);
        ImageView iv_close = findViewById(R.id.iv_close);
        iv_close.setOnClickListener(this);
        LinearLayout ll_zt = findViewById(R.id.ll_zt);
        ll_zt.setOnClickListener(this);
        Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.play_rotate_loading);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        img_loading.startAnimation(operatingAnim);
        img_play.setOnClickListener(view -> {
            if (videoView != null) {
                videoView.start();
                img_play.setVisibility(View.GONE);
                Glide.with(this).load(R.mipmap.play_video_stop).into(iv_button);
            }
        });
//        findViewById(R.id.parent).setOnLongClickListener(v -> {
//            // 长按事件，由于需要下载之后保存，使用本地的Copy文件
//            if (!TextUtils.isEmpty(localPath)) {
//                ClickEventUtils clickEventUtils = new ClickEventUtils(this,
//                        getIntent().getBooleanExtra("ForwardCollect", true));
//                clickEventUtils.setKeepHost(true);
//                clickEventUtils.showMoreDialogWithVideo(localPath, videoUrl, v.getContext());
//            }
//            return true;
//        });
        initEvent();
        playVideoByUrl();
    }


    private void playVideoByUrl(){
//        startPlay();
//        rlDownLoadState.setVisibility(View.GONE);
        downloadVideo();
    }
    /**
     * 初始化事件
     */
    private void initEvent() {
        videoView.setOnPreparedListener(mediaPlayer -> {
            // 是否静音播放
            if (getIntent().getBooleanExtra("isMute", false)) {
                mediaPlayer.setVolume(0f, 0f);
            }
            //视频加载完毕
            mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
            img_loading.setVisibility(View.GONE);
            img_loading.clearAnimation();
            rl_bottom.setVisibility(View.VISIBLE);
            LogUtils.d(TAG, "On Prepared" + videoView.getWidth() + " " + videoView.getHeight() + "  " + videoView.getRotation());
            // 设置seekBar和总时间
            if (videoView.getDuration() != 0) {
                seekBar.setMax(videoView.getDuration());
                iv_button.setImageResource(R.mipmap.play_video_stop);
                total.setText(DateUtils.setTime(videoView.getDuration() / 1000));
            }
            new Thread(() -> {
                try {
                    while (true) {
                        if (videoView != null && seekBar != null) {
                            if (videoView.isPlaying()) {
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (videoView.getCurrentPosition() != 0 && videoView.getCurrentPosition() != lastPosition) {
                                    LogUtils.d(TAG, "CurrentPosition  " + videoView.getCurrentPosition());
                                    seekBar.setProgress(videoView.getCurrentPosition());
                                    lastPosition = videoView.getCurrentPosition();
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

        });
        videoView.setOnCompletionListener(mediaPlayer -> {
            LogUtils.d(TAG, "On Completion" + videoView.getWidth() + " " + videoView.getHeight() + "  " + videoView.getRotation());
            img_play.setEnabled(true);
            img_play.setVisibility(View.VISIBLE);
            Glide.with(this).load(R.mipmap.play_video_play).into(iv_button);
            seekBar.setProgress(videoView.getDuration());
        });
        // 根据seekBar的进度 更新当前时间
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (current != null) {
                    current.setText(DateUtils.setTime(progress / 1000));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (videoView != null) {
                    videoView.seekTo(seekBar.getProgress());
                    videoView.start();
                    img_play.setVisibility(View.GONE);
                    Glide.with(VideoPlayActivity.this).load(R.mipmap.play_video_stop).into(iv_button);
                }
            }
        });
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //防止弹出 "无法播放此视频"
                FileUtils.deleteFile(new File(localPath));
                localPath = null;
                downloadVideo();
                return true;
            }
        });
    }

    /**
     * 动态中的视频
     */
    private void downloadVideo() {
        // 当前存在本地文件
//        if (!isPlayLocal())
        {
            // 缩略图
            if (!TextUtils.isEmpty(thumbUrl)){
                Glide.with(this)
                        .load(GlideUtils.getFixUrl(thumbUrl))
                        .apply(new RequestOptions().placeholder(null)
                                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                                .dontAnimate()
                                .transform(new CenterCrop()))
                        .into(ivThumb);
            }
            if (TextUtils.isEmpty(videoUrl)) return;
            rlDownLoadState.setVisibility(View.VISIBLE);
            isDownloading = true;
            downloadTask = SaveFileUtils.downloadCommonFile(videoUrl,
                    DOWNLOAD_PATH,
                    videoUrl.substring(videoUrl.lastIndexOf("/") + 1),
                    new StickersListener.StickersProgress() {
                        @Override
                        public void onProgress(int progress) {
                            runOnUiThread(() -> {
                                ringProgressBar.setProgress(progress);
                            });
                        }

                        @Override
                        public void onFail() {
                            isDownloading = false;
//                            FileUtils.deleteFile(DOWNLOAD_PATH + videoUrl.substring(videoUrl.lastIndexOf("/") + 1));
                            runOnUiThread(() -> {
                                ToastUtils.show("下载失败");
                            });
                        }

                        @Override
                        public void onSuccess(Uri backUri, String path, String name) {
                            isDownloading = false;
                            runOnUiThread(() -> {
                                rlDownLoadState.setVisibility(View.GONE);
                                localPath = path;
                                startPlay();
                                isPlayLocal();
                            });
                        }
                    });
        }

    }

    /**
     * 开始播放
     */
    private void startPlay() {
        if (TextUtils.isEmpty(localPath)) {
            videoView.setVideoURI(Uri.parse(videoUrl));
            videoView.start();
        } else {
//            ToastUtil.show(getString(R.string.str_video_address_error));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        setVideoState();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        setVideoState();
    }

    /**
     * VideoView的状态
     */
    private void setVideoState() {
        if (videoView != null && videoView.isPlaying()) {
            videoView.pause();
            Glide.with(this).load(R.mipmap.play_video_play).into(iv_button);
            img_play.setVisibility(View.VISIBLE);
        } else if (videoView != null && !videoView.isPlaying()) {
            Glide.with(this).load(R.mipmap.play_video_stop).into(iv_button);
            img_play.setVisibility(View.GONE);
            videoView.start();
        }
    }

    /**
     * 是否播放本地视频
     */
    private boolean isPlayLocal() {
        if (!TextUtils.isEmpty(localPath)) {
            img_loading.setVisibility(View.GONE);
            img_loading.clearAnimation();
            rlDownLoadState.setVisibility(View.GONE);
//            videoView.setVideoURI(FileUriUtils.getMediaUriFromPath(localPath));
            videoView.setVideoPath(localPath);
            videoView.start();
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        if(downloadTask != null && isDownloading){
            downloadTask.cancel();
        }
        super.onDestroy();
        if (img_loading != null) {
            img_loading.clearAnimation();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_close) {
            this.finish();
        } else if (id == R.id.ll_zt) {
            if (videoView != null && videoView.isPlaying()) {
                videoView.pause();
                Glide.with(this).load(R.mipmap.play_video_play).into(iv_button);
                img_play.setVisibility(View.VISIBLE);
            } else if (videoView != null && !videoView.isPlaying()) {
                Glide.with(this).load(R.mipmap.play_video_stop).into(iv_button);
                img_play.setVisibility(View.GONE);
                videoView.start();
            }
        }
    }


}
